﻿#include "JsonTools.h"
#include <fstream>

float JsonTool::ToFloat(const Json::Value& pJValue, const std::string &pMember, float defaultVal /*= 0*/)
{
	float pResVal = defaultVal;
	if (!pJValue[pMember].isNull())
	{ 
		pResVal = pJValue[pMember].asFloat();
	} 
	return pResVal;
}

int JsonTool::ToInt(const Json::Value& pJValue, const std::string &pMember, int defaultVal /*= 0*/)
{
	int pResVal = defaultVal;
	if (!pJValue[pMember].isNull())
	{
		pResVal = pJValue[pMember].asInt();
	}
	return pResVal;
}

std::string JsonTool::ToString(const Json::Value& pJValue, const std::string &pMember, const std::string defaultVal /*= ""*/)
{
	std::string pResVal = defaultVal;
	if (!pJValue[pMember].isNull())
	{
		pResVal = pJValue[pMember].asString();
	}
	return pResVal;
}

void JsonTool::JsonToFile(const Json::Value& pJValue, const std::string &pFile)
{
	Json::StreamWriterBuilder writerBuilder;
	std::ofstream os;
	os.open(pFile);

	std::unique_ptr<Json::StreamWriter> jsonWriter(writerBuilder.newStreamWriter());
	jsonWriter->write(pJValue, &os);
}

void JsonTool::FileToJson(const std::string &pFile, Json::Value &outValue)
{
	//Json::Value jsonCircle;
	std::ifstream ifs; //标准输入流
	ifs.open(pFile);

	Json::CharReaderBuilder builder;
	builder["collectComments"] = false;
	JSONCPP_STRING errs;
	parseFromStream(builder, ifs, &outValue, &errs);
}
